//
//  CZNetworkTools.swift
//  WeiBo
//
//  Created by Apple on 16/9/5.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import AFNetworking

//  请求的枚举类型
enum RequestType: Int {
    case GET
    case POST
    
}
//  网络请求工具类
class CZNetworkTools: AFHTTPSessionManager {
    //  全局访问点
    static let sharedTools: CZNetworkTools = {
        let tools = CZNetworkTools()
        //  添加一种可接受的类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //  封装上传图片请求
    fileprivate func requestUpload(url: String, params: [String: Any], imageData: Data, name: String, callBack: @escaping (Any?, Error?)->()) {
    
        post(url, parameters: params, constructingBodyWith: { (formData) in
            //  mimeType 通用的资源类型
            //  fileName 随便传，一般服务端不使用，服务端会随机创建一个唯一的图片名称
            //  name 服务端所需要的参数
            //  data 图片的二进制数据
            formData.appendPart(withFileData: imageData, name: name, fileName: "test", mimeType: "application/octet-stream")
            }, progress: nil, success: { (dataTask, response) in
                callBack(response, nil)
        }) { (dataTask, error) in
            callBack(nil, error)
        }
        
    }
    
    //  封装的get/post请求
    fileprivate func request(requestType: RequestType, url: String, params: Any?, callBack: @escaping (Any?, Error?)->()) {
        
        
        //  更加简单的写法
        let successClosure = {(dataTask: URLSessionDataTask , response: Any?) in
            callBack(response, nil)
        }
        let failureClosure = {(response: URLSessionDataTask?, error: Error) in
            callBack(nil, error)
        }
        if requestType == .GET {
            get(url, parameters: params, progress: nil, success: successClosure, failure: failureClosure)
        } else {
            post(url, parameters: params, progress: nil, success: successClosure, failure: failureClosure)
        }
        
        //        if requestType == .GET {
        //
        //            get(url, parameters: params, progress: nil, success: { (_, response) in
        //                    callBack(response, nil)
        //                }, failure: { (_, error) in
        //                    callBack(nil, error)
        //            })
        //        } else {
        //            post(url, parameters: params, progress: nil, success: { (_, response) in
        //                    callBack(response, nil)
        //                }, failure: { (_, error) in
        //                    callBack(nil, error)
        //            })
        //        }
    }
    

    
}


// MARK:    --发微博接口
extension CZNetworkTools {
    
    //  发送带图片的微博接口
    func upload(accessToken: String, status: String, image: UIImage, callBack: @escaping (Any?, Error?)->()) {
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        let params = [
            "access_token": accessToken,
            "status": status,
        ]
//        let imageData = UIImagePNGRepresentation(image)
        //  图片转成二进制
        let imageData = UIImageJPEGRepresentation(image, 0.5)!
        requestUpload(url: url, params: params, imageData: imageData, name: "pic", callBack: callBack)
//        print(imageData.count)
//        post(url, parameters: params, constructingBodyWith: { (formData) in
//                formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpej")
//            }, progress: nil, success: { (dataTask, response) in
//                callBack(response, nil)
//            }) { (dataTask, error) in
//                callBack(nil, error)
//        }
        
    }
    
    //  发送带文字微博接口
    func update(accessToken: String, status: String,  callBack: @escaping (Any?, Error?)->()) {
        let url = "https://api.weibo.com/2/statuses/update.json"
        let params = [
            "access_token": accessToken,
            "status": status
        ]
        
        request(requestType: .POST, url: url, params: params, callBack: callBack)
    }
}

// MARK:    --微博首页接口
extension CZNetworkTools {
    
    //  获取当前登录用户所关注的最新微博数据
    func requestStatus(accesstoken: String, maxId: Int64 = 0, sinceId: Int64 = 0, callBack: @escaping (Any?, Error?)->()) {
        
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        let params: [String: Any] = [
            "access_token": accesstoken,
            "max_id": maxId,
            "since_id": sinceId
        ]
        
        let urlPath = url + "?access_token=" + accesstoken
        print("----------")
        print(urlPath)
        print("----------")
        //  请求数据
        request(requestType: .GET, url: url, params: params, callBack: callBack)
        
        
    }
}




// MARK:    --OAuth登录相关接口

extension CZNetworkTools {
    
    //  通过accesstoken和用户id获取用户信息
    func requestUserInfo(userAccount: CZUserAccount, callBack: @escaping (Any?, Error?)->()) {
        
        let url = "https://api.weibo.com/2/users/show.json"
        let params: [String : Any] = [
            "access_token": userAccount.access_token!,
            "uid": userAccount.uid
        ]
        
        let urlPath = url + "?access_token=" + userAccount.access_token! + "&uid=\(userAccount.uid)"
        print(urlPath)
        
        request(requestType: .GET, url: url, params: params, callBack: callBack)
        
    }

    
    //  通过授权码获取accesstoken
    func requestAccessToken(code: String, callBack: @escaping (Any?, Error?)->()) {
        let url = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id": WeiBoAppKey,
            "client_secret": WeiBoAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WeiBoRedirect_Uri
        ]
        
        request(requestType: .POST, url: url, params: params, callBack: callBack)
    }

}























